import pickle
import base64
from django_redis import get_redis_connection


def merge_cookie_redis_cart(request, user, response):
    # 获取cookie数据
    cookie_cart = request.COOKIES.get('cart')
    # 判断cookie中是否有数据
    if not cookie_cart:
        return response

    # 转换cookie数据
    cookie_dict = {}
    if cookie_cart:
        cookie_dict = pickle.loads(base64.b64decode(cookie_cart.encode()))
    # 获取redis数据
    redis_conn = get_redis_connection('cart')

    # 合并数据到redis
    for sku_id, count_selected in cookie_dict.items():
        redis_conn.hset('cart_%s' % user.id, sku_id, count_selected['count'])
        redis_conn.sadd('cart_selected_%s' % user.id, sku_id)
    # 清除cookie数据
    response.delete_cookie('cart')
    return response
